var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var { WebSocketServer } = require("ws");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var yyc = require('./routes/yyc')
var zhcRouter = require('./routes/zhcModule')
// var session=require('express-session');
var expressJwt = require('express-jwt');

const LzlRouter = require('./routes/Lzl')

const { auth } = require("./utils/auth") //引入auth中间件
var app = express();

app.use(cors());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// app.use(cors({
//   origin: ['http://localhost:5173', 'http://localhost:5174'],
//   credentials: true,
//   methods: ['GET', 'POST', 'PUT', 'DELETE'],
//   allowedHeaders: ['Content-Type', 'Authorization','accesstoken','refreshtoken']
// }));

// view engine setup1 
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/users', usersRouter);
app.use("/lzl", LzlRouter)
 
app.use('/yyc', yyc);
app.use('/', indexRouter);
app.use(auth); //使用auth中间件


app.use('/zhc', zhcRouter);



// catch 404 and forward to error handler
// app.use(function (req, res, next) {
//   next(createError(404));
// });


const connection = {};//用于存储用户连接信息

const server = app.listen(3002);//监听3002端口
const wss = new WebSocketServer({ server });//创建WebSocket服务器

wss.on("connection", (ws) => {
  ws.on("message", (message) => {
    const data = JSON.parse(message);
    if (data.action === "login") {
      if (connection[data.id] && connection[data.id].fingerprint && data._id === connection[data.id]._id) {
        //提示旧设备
        connection[data.id].socket.send(
          JSON.stringify({
            action: "logout",
            message: `你于${new Date().toLocaleString()}账号在别处登录`,
          })
        );
        connection[data.id].socket.close(); //断开旧设备连接
        connection[data.id].socket = ws; //更新ws
      } else {
        console.log("首次登录");
        connection[data.id] = {
          socket: ws, //记录ws
          fingerprint: data.fingerprint, //记录指纹
          _id: data._id, //记录用户唯一的标识
        };
      }
    }
  });
});



module.exports = app;
